package org.onvivals.module.ums.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.onvivals.common.param.PageParam;
import org.onvivals.common.web.PageResult;
import org.onvivals.module.ums.entity.SysGroupData;
import org.onvivals.module.ums.mapper.SysGroupDataMapper;
import org.onvivals.module.ums.param.SysGroupDataParam;
import org.onvivals.module.ums.service.ISysGroupDataService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * SysGroupDataServiceImpl
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysGroupDataServiceImpl extends ServiceImpl<SysGroupDataMapper, SysGroupData> implements ISysGroupDataService {


	/**
	 * 获取配置数据
	 *
	 * @param name 配置名称
	 * @return List
	 */
	@Override
	public List<JSONObject> getDatas(String name) {
		List<SysGroupData> systemGroupDatas = this.baseMapper
				.selectList(Wrappers.<SysGroupData>lambdaQuery()
						.eq(SysGroupData::getGroupName, name)
						.eq(SysGroupData::getStatus, 1)
						.orderByDesc(SysGroupData::getSort));
		List<JSONObject> list = systemGroupDatas
				.stream()
				.map(SysGroupData::getValue)
				.map(JSONObject::parseObject)
				.collect(Collectors.toList());

		return list;
	}

	@Override
	public JSONObject getData(String name) {
		SysGroupData sysGroupData = this.baseMapper
				.selectOne(Wrappers.<SysGroupData>lambdaQuery()
						.eq(SysGroupData::getGroupName, name)
						.eq(SysGroupData::getStatus, 1)
						.orderByDesc(SysGroupData::getSort));
		if (sysGroupData != null) {
			JSONObject jsonObject = JSONObject.parseObject(sysGroupData.getValue());
			return jsonObject;
		}
		return null;
	}


	@Override
	public PageResult<SysGroupData> pageRel(SysGroupDataParam param) {
		PageParam<SysGroupData, SysGroupDataParam> page = new PageParam<>(param);
		page.setDefaultOrder("create_time desc");
		Page<SysGroupData> page1 = new Page<>(page.getPages(), page.getSize());
		Page<SysGroupData> list = this.page(page1, page.getOrderWrapper());
		return new PageResult<>(list.getRecords(), page1.getTotal());
	}

}
